package indi.qing.controller;

import indi.qing.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@Slf4j
public class FileController {

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @PostMapping("/file/upload")
    public Result upload(@RequestParam MultipartFile file){
        if (file.isEmpty()) {
            return Result.failed("文件为空");
        }
        String originalFilename = file.getOriginalFilename();
        String fileName = System.currentTimeMillis() + "." + originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        File dataDir = new File(uploadFolder);
        if (!dataDir.exists()) {
            dataDir.mkdir();
        }
        try {
            file.transferTo(new File(uploadFolder, fileName));
        } catch (IOException e) {
            e.printStackTrace();
            return Result.failed("文件上传失败");
        }
//        String path = "http://127.0.0.1:8888/api/file/" + fileName;
        String path = "http://dreamwake.top:8888/api/file/" + fileName;
        return Result.ok(path);
    }

}
